<script setup lang='ts'>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  GetCompany,
  GetDoulun,
  GetHarbor
} from '@/api/http'
import {
  GetRelationWindVelocity,
  AddWindVelocity,
  UpdateWindVelocity,
  DeleteWindVelocity
} from '@/api/publicApi'
defineProps({
  num: {
    type: Number,
    default: 0
  }
})
// 定义变量
// 弹框
const dialogVisible = ref(false)

// 弹框表单
const formData = reactive({
  name: '',
  code: '',
  barWheelMachineCode: '',
  creationTime: '',
  lastModificationTime: '',
  harborCode: '',
  companyCode: '',
  positionDescription: ''
})

// 表单验证
const validPassword = (rule, value, callback) => {
  // 匹配字符串格式：字母大小写  数字  下划线 横线 正反斜线
  let reg = /^(?!_)(?!.*?_$)[a-zA-Z0-9_ /\\//\-/\\]+$/
  if (!reg.test(value)) {
    callback(new Error('编号格式不正确，含有特殊字符!'))
  }
}

// 表单验证
const rules = reactive({
  name: [ { required: true, message: '名称不能为空' } ],
  deviceName: [
    { required: true, message: '名称不能为空', trigger: 'blur' }
  ],
  deviceCode: [
    { required: true, message: '设备编号不能为空', trigger: 'blur' }

  ],
  positionDescription: [
    { required: true, message: '位置描述不能为空', trigger: 'blur' }
  ],

  code: [
    { required: true, message: '编号不能为空', trigger: 'change' }

  ],
  barWheelMachineCode: [
    {
      type: 'date',
      required: true,
      message: '请选择堆取料机',
      trigger: 'change'
    }
  ],
  harborCode: [
    {
      type: 'date',
      required: true,
      message: '请选择所属港口',
      trigger: 'change'
    }
  ],
  companyCode: [
    {
      type: 'date',
      required: true,
      message: '请选择所属公司',
      trigger: 'change'
    }
  ],
  timeInUse: [
    {
      type: 'date',
      required: true,
      message: '请选择时间',
      trigger: 'change'
    }
  ]
})

// 分页
const pageInfo = reactive({
  total: 100,
  pageSize: 10,
  pageNum: 1
})

// 数据源
const tableData: any = ref([])

// 港口列表
const portList: any = ref([])
// 公司列表
const companyList: any = ref([])
// 堆取料机列表
const barWheelList: any = ref([])

// 是否新增
const isAdd = ref(true)

// 定义函数
onMounted(() => {
  getAnemometerData()
  getPortList()
})

const cellStyle = {
  textAlign: 'center'
}

const headStyle = {
  textAlign: 'center'
}

// 定义函数

// 获取表格数据
const getAnemometerData = async () => {
  tableData.value = []
  let data = {
    SkipCount: (pageInfo.pageNum - 1) * pageInfo.pageSize,
    MaxResultCount: pageInfo.pageSize,
    Sorting: 'lastModificationTime desc'
  }
  let res = await GetRelationWindVelocity({ ...data })
  pageInfo.total = res.result.totalCount
  tableData.value = [ ...res.result.items ]
  tableData.value.forEach((item: any) => {
    item.timeInUse = (item.timeInUse.split('T')[0] + ' ' + item.timeInUse.split('T')[1]).split('.')[0]
    item.creationTime = (item.creationTime.split('T')[0] + ' ' + item.creationTime.split('T')[1]).split('.')[0]
  })
  console.log('机构页面接口信息---->', res, tableData.value)
}

// 改变每页数量
const handlePlanSizeChange = (val: number) => {
  pageInfo.pageSize = val
  getAnemometerData()
}
// 切换页码
const handlePlanCurrentChange = (val: number) => {
  pageInfo.pageNum = val
  getAnemometerData()
}

// 获取港口列表
const getPortList = async () => {
  portList.value = []
  let page = {
    SkipCount: 0,
    MaxResultCount: 10,
    Sorting: 'lastModificationTime'
  }
  let res = await GetHarbor(page)
  portList.value = [ ...res.result.items ]
}
// 获取公司列表
const getCompanyList = async (e: any) => {
  companyList.value = []
  let res = await GetCompany({ HarborCode: e })
  companyList.value = [ ...res.result.items ]
}
// 获取公司下的堆取料机
const getBarWheelList = async (e: any) => {
  formData.companyCode = e
  barWheelList.value = []

  let res = await GetDoulun({
    HarborCode: formData.harborCode,
    CompanyCode: formData.companyCode
  })
  barWheelList.value = [ ...res.result.items ]
}

// 确定
const determine = async () => {
  let res: any
  if (isAdd.value) {
    if (formData.code && formData.name) {
      if (formData.harborCode && formData.companyCode) {
        if (formData.barWheelMachineCode) {
          res = await AddWindVelocity(formData)
        } else {
          ElMessage({
            type: 'error',
            message: '请选择堆取料机!'
          })
        }
      } else {
        ElMessage({
          type: 'error',
          message: '请选择港口和公司!'
        })
      }

    } else {
      ElMessage({
        type: 'error',
        message: '内容不可以为空!'
      })
    }
  } else {
    res = await UpdateWindVelocity(formData)
  }
  if (res.success) {
    dialogVisible.value = false
    ElMessage({
      type: 'success',
      message: '操作成功!'
    })
    getAnemometerData()
  } else {
    ElMessage({
      type: 'error',
      message: '操作失败!'
    })
  }
}

// 新增数据
const addItem = () => {
  console.log('新增---->')
  isAdd.value = true
  dialogVisible.value = true
}

// 编辑某项
const updateItem = (row: any) => {
  console.log('修改------->')
  isAdd.value = false
  formData.name = row.name
  formData.code = row.code
  formData.lastModificationTime = row.lastModificationTime
  formData.creationTime = row.creationTime
  formData.harborCode = row.harborCode
  formData.companyCode = row.companyCode
  formData.barWheelMachineCode = row.barWheelMachineCode
  formData.positionDescription = row.positionDescription
  dialogVisible.value = true
}
// 删除某项
const deleteItem = (row: any) => {
  console.log('删除------->', row)
  ElMessageBox.confirm(
    '确定要删除该处理意见?',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      let res = await DeleteWindVelocity({ id: row.id + '' })
      if (res.success) {
        ElMessage({
          type: 'success',
          message: '删除成功!'
        })
        getAnemometerData()
      } else {
        ElMessage({
          type: 'error',
          message: '删除失败!'
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

// 取消
const cancellation = () => {
  console.log('查询------->')
  dialogVisible.value = false
}

// 关闭弹框
const closeDialog = () => {
  isAdd.value = false
  formData.name = ''
  formData.code = ''
  formData.lastModificationTime = ''
  formData.harborCode = ''
  formData.companyCode = ''
  formData.creationTime = ''
  formData.barWheelMachineCode = ''
  formData.positionDescription = ''
}

// 向外暴露的函数与变量
defineExpose({
  getAnemometerData
})
</script>

<template>
  <div class="table-box">
    <div class="add-btn-box">
      <div
        class="add-btn custom-button"
        @click="addItem"
      >
        增加风速仪
      </div>
    </div>
    <el-table
      :cell-style="cellStyle"
      :header-cell-style="headStyle"
      :data="tableData"
      max-height="640"
      size="small"
    >
      <el-table-column
        prop="name"
        label="名称"
      />
      <el-table-column
        prop="barWheelMachineName"
        label="所属堆取料机"
      />
      <el-table-column
        prop="creationTime"
        label="创建时间"
      />
      <el-table-column
        prop="lastModificationTime"
        label="更新时间"
      />
      <el-table-column
        prop="positionDescription"
        label="位置描述"
      />
      <el-table-column
        label="操作"
      >
        <template #default="scope">
          <div class="btn-box">
            <div
              class="update-btn"
              @click="updateItem(scope.row)"
            >
              修改
            </div>
            <div
              class="delete-btn"
              @click="deleteItem(scope.row)"
            >
              删除
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="pagination-box">
    <el-pagination
      v-model:current-page="pageInfo.pageNum"
      v-model:page-size="pageInfo.pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.total"
      @size-change="handlePlanSizeChange"
      @current-change="handlePlanCurrentChange"
    />
  </div>
  <el-dialog
    v-model="dialogVisible"
    width="960"
    :title="isAdd ? '增加风速仪' : '修改风速仪信息'"
    @close="closeDialog"
  >
    <template #default>
      <div class="form-box">
        <el-form
          class="formStyle"
          :model="formData"
          :rules="rules"
          label-width="130px"
        >
          <el-form-item
            label="名称:"
            prop="name"
          >
            <el-input v-model="formData.name" />
          </el-form-item>

          <el-form-item
            label="编号:"
            prop="code"
          >
            <el-input
              v-model="formData.code"
            />
          </el-form-item>
          <el-form-item
            v-if="isAdd"
            label="所属港口"
            prop="harborCode"
          >
            <el-select
              v-model="formData.harborCode"
              class="stacker-reclaimer-select"
              @change="getCompanyList"
            >
              <el-option
                v-for="item in portList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="isAdd && formData.harborCode"
            label="所属公司"
            prop="companyCode"
          >
            <el-select
              v-model="formData.companyCode"
              class="stacker-reclaimer-select"
              @change="getBarWheelList"
            >
              <el-option
                v-for="item in companyList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="isAdd && formData.companyCode"
            label="所属堆取料机"
            prop="barWheelMachineCode"
          >
            <el-select
              v-model="formData.barWheelMachineCode"
              class="stacker-reclaimer-select"
            >
              <el-option
                v-for="item in barWheelList"
                :key="item.id"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="位置描述:"
          >
            <el-input
              v-model="formData.positionDescription"
            />
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template #footer>
      <el-button @click="cancellation">
        取 消
      </el-button>
      <el-button @click="determine">
        确 定
      </el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang=scss>
.table-box {
  padding: 0 15px;

  .add-btn-box {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    width: 100%;
    height: 40px;
    margin-bottom: 10px;

    /* border: 1px solid red; */

    >div {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 120px;
      height: 100%;

      /* border: 1px solid red; */
    }
  }
}

.status-box {
  display: flex;
  align-items: center;
  justify-content: space-around;
  width: 100%;
  height: 100%;

  /* border: 1px solid red; */

  .color-box {
    width: 76px;
    height: 30px;
    background-color: #22f34c;

    /* border: 1px solid red; */
  }

  .status-name {
    width: 76px;
    height: 30px;
  }

  /* stylelint-disable-next-line selector-id-pattern */
  #firstLevel {
    background-color: #ede215;
  }

  /* stylelint-disable-next-line selector-id-pattern */
  #secondLevel {
    background-color: #fe0808;
  }
}

.pagination-box {
  margin-top: 10px;
  padding: 0 15px;
}

.btn-box {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;

  .treate-btn {
    width: 56px;
    height: 28px;
    color: #fff;
    background-color: #409eff;
    border-radius: 5px;

    &:hover {
      cursor: pointer;
    }
  }
}

.info-box {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 90px;

  /* border: 1px solid red; */

  >div {
    height: 100%;
    border: 1px solid #000;
    border-bottom: none;

    >div {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 30px;
      color: #000;
      font-size: 18px;
      border-bottom: 1px solid #000;
    }
  }

  .left-box {
    width: 100px;
    border-right: none;
  }

  .right-box {
    width: 250px;
  }
}

.opinions-box {
  display: flex;
  width: 100%;
  height: 40px;
  margin-top: 10px;

  /* border: 1px solid red; */

  >div {
    height: 100%;

    /* border: 1px solid green; */
  }

  .title-box {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100px;
    color: #000;
  }

  .select-box {
    width: 360px;
  }
}

.input-box {
  width: 340px;
  margin-top: 10px;
  margin-left: 100px;

  /* border: 1px solid red; */
}
</style>
<style lang="scss">
.opinions-select {
  width: 100%;
}
</style>
<style lang="scss">
.form-box {
  padding-right: 5%;

  /* border: 1px solid red; */
}

.stacker-reclaimer-select {
  width: 100%;
}

.btn-box {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;

  >div {
    width: 56px;
    height: 28px;
    color: #fff;
    border-radius: 5px;

    /* background-color: red; */

    &:hover {
      cursor: pointer;
    }
  }

  .update-btn {
    background-color: #e6a23c;
  }

  .delete-btn {
    margin-left: 10px;
    background-color: #f56c6c;
  }
}
</style>